<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit|ie-comp|ie-stand">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <title>打卡时间</title>
</head>

<body>
  <div id="app" v-loading.fullscreen.lock="loading">
    <div class="attendance-record">
      <div>
        <search-btn-view btn-text="查询记录" :before-search="checkSearchValid" @before-open="resetSearch" @search="searchData">
          <template slot="append">
            <el-button size="medium" type="primary" @click="exportExcel">导出excel</el-button>
          </template>
          <div slot="search-content">
            <search-form :search="search" :person-list="personList"></search-form>
          </div>
        </search-btn-view>
      </div>

      <div class="attendance-record-table-div" :class="{'hasPage':pagination.totalCount!==0}">
        <el-table fit stripe border class="attendance-record-table" :data="records" style="width: 100%" height="parent">
          <el-table-column :resizable="false" label="姓名" prop="userName" key="userName" min-width="100px" align="center"
            fixed="left"></el-table-column>
          <el-table-column :resizable="false" label="部门" prop="deptName" key="deptName" min-width="80px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="车间" prop="workshopName" key="workshopName" min-width="80px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="编号" prop="userId" key="userId" min-width="60px" align="center"></el-table-column>
          <el-table-column :resizable="false" label="工号" prop="workerNo" key="workerNo" min-width="60px" align="center"></el-table-column>

          <template v-for="head in tableHead">
            <el-table-column :resizable="false" :label="head" :key="`date_${head}`" min-width="80px">
              <template slot="header" slot-scope="scope">
                <div class="tableHeader">{{moment(head).format('dd')}}</div>
                <div class="tableHeader" style="text-align:right;">{{moment(head).format('D')}}</div>
              </template>
              <template slot-scope="scope">
                <div v-if="scope.row.clockObj[head]!==undefined" v-html="scope.row.clockObj[head]" style="text-align:center;"></div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div style="margin-top:10px;text-align:right;" v-if="pagination.totalCount!==0">
        <el-pagination background :page-size="pagination.pageSize" :total="pagination.totalCount" :current-page.sync="pagination.currentPage"
          @current-change="pageChange"></el-pagination>
      </div>
    </div>
  </div>
</body>

<script src="../../myJs/importFile.js"></script>
<script>
  importFile([
    "/vueSystem/components/css/searchBtnView.css",
    "/vueSystem/components/css/deptTransfer.css",
    "../components/css/deptPersonSelect.css",
    "../components/css/attendanceSearchForm.css"
  ], [
    "/vueSystem/components/searchBtnView.js",
    "/vueSystem/components/deptTransfer.js",
    "/vueSystem/mixins/datePickerOptionsMixin.js"
  ])
</script>
<script src="../components/deptPersonSelect.js"></script>
<script src="../components/attendanceSearchForm.js"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: function () {
      var search = {
        startDate: moment().startOf('month').valueOf(),
        endDate: moment().valueOf(),
        deptPerson: {
          depts: [],
          persons: []
        }
      };

      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        records: [],
        personList: [],
        tableHead: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 30
        },
        moment: moment
      }
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([this.setPersonList(), this.setRecords(true)]).then(function (res) {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setPersonList: function () {
        var self = this;
        return ajaxRequest('dingTalk/askForApprover').then(function (personList) {
          personList = _.map(personList, function (person) {
            return {
              deptId: person.deptId,
              deptName: person.deptName,
              userId: person.id,
              userName: person.personName
            };
          });
          self.personList = personList;
          return personList;
        });
      },

      setRecords: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var search = this.search;
        var postData = {
          startDate: moment(search.startDate).format('YYYY-MM-DD'),
          endDate: moment(search.endDate).format('YYYY-MM-DD'),
        };

        var deptPerson = search.deptPerson;
        postData.deptIds = JSON.stringify(_.map(deptPerson.depts, 'id'));
        postData.userIds = JSON.stringify(_.map(deptPerson.persons, 'id'));

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        postData.start = start;
        postData.length = pageSize;

        var self = this;
        return ajaxRequest('dingTalk/queryClockTime', postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var records = res.returnData;
          self.formatRecords(records);

          self.setTableHead(postData);
          self.records = records;
          self.pagination.totalCount = res.iTotalRecords;
          return records;
        });
      },

      formatRecords: function (records) {
        for (var i = 0; i < records.length; i++) {
          var record = records[i];
          var clockList = record.clockList;
          var clockObj = this.getFormatClock(clockList);
          record.clockObj = clockObj;
        }
      },

      getFormatClock: function (clockList) {
        var clockGroup = _.groupBy(clockList, function (clock) {
          return moment(clock).format('YYYY-MM-DD');
        });

        var clockObj = {};
        for (var key in clockGroup) {
          var clocks = clockGroup[key];
          clocks = _.orderBy(clocks);
          clocks = _.map(clocks, function (clock) {
            var time = moment(clock).format('HH:mm');
            return `<div>${time}</div>`;
          });
          clockObj[key] = clocks.join('');
        }
        return clockObj;
      },

      setTableHead: function (postData) {
        var startDate = postData.startDate;
        var endDate = postData.endDate;
        var date = moment(startDate).valueOf();
        var tableHead = [];
        while (moment(date).isSameOrBefore(endDate, 'day')) {
          tableHead.push(moment(date).format('YYYY-MM-DD'));
          date = moment(date).add(1, 'day').valueOf();
        }
        this.tableHead = tableHead;
      },

      resetRecords: function (isSearch) {
        this.loading = true;
        var self = this;
        this.setRecords(isSearch).then(function () {
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      checkSearchValid: function () {
        var search = this.search;
        var startDate = search.startDate;
        var endDate = search.endDate;
        if (moment(startDate).add(1, 'month').isBefore(endDate, 'day')) {
          this.$alert('只能查询一个月以内的汇总数据', '信息');
          return false;
        }
        return true;
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.resetRecords(true);
      },

      pageChange: function () {
        this.resetRecords();
      },

      exportExcel: function () {
        var search = this.oldSearch;
        var postData = {
          startDate: moment(search.startDate).format('YYYY-MM-DD'),
          endDate: moment(search.endDate).format('YYYY-MM-DD')
        };
        var deptPerson = search.deptPerson;
        postData.deptIds = JSON.stringify(_.map(deptPerson.depts, 'id'));
        postData.userIds = JSON.stringify(_.map(deptPerson.persons, 'id'));
        var formParam = SysUtil.formatFormParam(postData);
        var basePath = SysUtil.getBasePath();
        var path = `${basePath}/dingTalk/exprotExcelAttendClockTime?${formParam}`;
        window.open(path);
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      SearchForm: AttendanceSearchForm
    }
  });
</script>
<style>
  .attendance-record {
    padding: 10px 20px;
    padding-bottom: 5px;
    height: calc(100% - 15px);
  }

  .attendance-record .attendance-record-table-div {
    height: calc(100% - 46px);
    overflow: auto;
  }

  .attendance-record .attendance-record-table-div.hasPage {
    height: calc(100% - 88px);
  }

  .attendance-record .tableHeader {
    display: block;
    height: 20px;
    line-height: 20px;
    font-weight: bold;
  }
</style>

</html>